package com.example.utils;

import java.io.*;
import java.net.URL;
import java.util.Base64;

public class PhotoUtils  {

    // 1. 从 URL 下载图片转 byte[]
    public static byte[] toByte(String path) throws IOException {
        // 尝试 URL 下载
        try (InputStream inputStream = new URL(path).openStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            return outputStream.toByteArray();
        } catch (Exception e) {
            // URL 失败后尝试本地文件
            try (InputStream inputStream = new FileInputStream(path);
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                return outputStream.toByteArray();
            } catch (Exception ex) {
                throw new IOException("无法从 URL 或本地路径加载图片: " + path, ex);
            }
        }
    }

    public static String toBase64(String path) throws IOException {
        byte[] imageBytes;
        try {
            // 先尝试当作 URL 下载
            try (InputStream inputStream = new URL(path).openStream();
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                imageBytes = outputStream.toByteArray();
            }
        } catch (IOException e) {
            // 如果下载失败，则尝试从本地读取
            try (InputStream inputStream = new FileInputStream(path);
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                imageBytes = outputStream.toByteArray();
            } catch (IOException ex) {
                throw new IOException("无法读取图片，请确认 URL 或本地路径是否正确: " + path);
            }
        }

        // 转 Base64
        return Base64.getEncoder().encodeToString(imageBytes);
    }

}
